package com.core.db;

import java.sql.Connection;
import java.sql.SQLException;

import com.core.mvc.config.DBConfig;

public class Connector
{
	private static Connector instance;
	private ConnPool pool;
	private boolean isInit = false;

	private Connector()
	{

	}

	public static Connector get()
	{
		if ( instance == null )
		{
			synchronized ( Connector.class )
			{
				if ( instance == null )
				{
					instance = new Connector();
				}
			}
		}
		return instance;
	}

	public void create( DBConfig cfg ) throws Exception
	{
		if ( !isInit )
		{
			isInit = true;
			ConnPool.Builder builder = new ConnPool.Builder();
			builder.setDriver( cfg.getDriver() );
			builder.setUrl( cfg.getUrl() );
			builder.setUsername( cfg.getUser() );
			builder.setPassword( cfg.getPasswd() );
			builder.setInitConnSize( cfg.getInitConnSize() );
			builder.setIncrementalConnSize( cfg.getIncrementalConnSize() );
			builder.setMaxConnSize( cfg.getMaxConnSize() );
			this.pool = builder.build();
			pool.createPool();
		}
	}

	public Connection getConnection() throws SQLException
	{
		if ( pool != null )
		{
			return pool.getConnection();
		}
		return null;
	}

	public void destory() throws SQLException
	{
		if ( isInit && pool != null )
		{
			pool.closeConnectionPool();
		}
		isInit = false;
	}
}
